# -*- coding: utf-8 -*-
import re
import pandas as pd
import xml.etree.ElementTree as ET

class JULIET:
    '''解析 juliet 的 manifest.xml 文件,生成结果'''
    '''juliet-java 中的 manifest.xml 文件格式有误,复制一份订正数据格式后使用'''
    def __init__(self) -> None:
        self.mainfest_xml_path='./resource/juliet-java-1.3-manifest.xml'
        self.result={}
        self.generate_result()

    def generate_result(self):
        '''解析 xml 文件生成 result 结果'''
        tree=ET.parse(self.mainfest_xml_path)
        root=tree.getroot()
        testcases=root.findall('testcase')
        for testcase in testcases:
            files=testcase.findall('file')
            one_testcase=[]
            for file in files:
                file_name=file.attrib['path']
                if 'CWE' in file_name:
                    file_cweid='CWE-'+re.findall(r'CWE(\d+)_',file_name,flags=0)[0]
                    if  not self.result.get(file_cweid):
                        self.result[file_cweid]=[]
                    one_file_info={'file_name':file_name,'error_info':[]}
                    flaws=file.findall('flaw')
                    for flaw in flaws:
                        flaw_line=flaw.attrib['line']
                        flaw_cweid=re.findall(r'^(CWE-\d+)',flaw.attrib['name'],flags=0)[0]
                        one_file_info['error_info'].append({'line':flaw_line,'cweid':flaw_cweid})
                    one_testcase.append(one_file_info)
            self.result[file_cweid].append(one_testcase)
    
    def get_testcase_by_file_name(self,file_name):
        '''根据文件名获取对应 flaw 信息,如果没有该文件名相关信息返回 None'''
        if not re.findall(r'CWE(\d+)',file_name,flags=0):
            return None
        cweid='CWE-'+re.findall(r'CWE(\d+)',file_name,flags=0)[0]
        testcases=self.result[cweid]
        for testcase in testcases:
            for file in testcase:
                if file['file_name']==file_name:
                    return testcase
                else:
                    continue
        return None
    def get_testcase_cweid(self,testcase):
        '''返回对应 testcase 的 cweid'''
        cweid='CWE-'+re.findall(r'CWE(\d+)',testcase[0]['file_name'],flags=0)[0]
        return cweid

    def if_mate_line(self,line,file_name,juliet_testcase):
        '''检查 testcase 中对应的 file,行数是否匹配,匹配成功返回 True,失败返回 False'''
        for file in juliet_testcase:
            if file['file_name']==file_name:
                for error in file['error_info']:
                    if error['line'] == line:
                        return True
        return False
    
    def if_bad_function_name(self,function_name):
        '''判断当前函数是否是 bad 函数'''
        if re.match(r'^(.*)?bad$',function_name):
            return True
        else:
            return False